from PySide6.QtCore import QObject, Signal
from model.common import Common
from model.ssh_connector import SSHConnector
from core import bus

class ServerPresenter(QObject):
    """负责服务器连接测试与状态更新"""
    server_connect_status = Signal(dict)

    def __init__(self, view, server_manager):
        super().__init__() 
        self.view = view
        self.server_manager = server_manager
        self.common = Common()
        self.ssh = SSHConnector()
    def handle_load_servers(self):
        """从配置文件中加载服务器信息"""
        return self.server_manager.get_all_servers()

    def handle_deselect_all(self):
        """全不选"""
        self.server_manager.deselect_all_servers()

    def handle_select_all(self, servers):
        """全选"""
        self.server_manager.select_all_servers(servers)

    def handle_connection(self, servers):
        """测试服务器连接"""
        selected = [s for s in servers if s.get("selected", True)]

        def on_test(server):
            result = self.ssh.execute_command(server,'echo "connection_test"')
            res = result['status'] and "connection_test" in result['stdout']
            self.server_manager.update_connection_status(server.get("ip"), res)    
            return result
        
        def on_finished(results):
            self.server_connect_status.emit(results)
            bus.dialog_message.emit(results)

        self.common.run_task(
            func=on_test,
            targets=selected,
            on_finished=on_finished
        )
